package learn.spring.dubbo.framework.protocol;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author ShenHao
 */
public class HttpClient {

    public static String post(String hostName, Integer port, Invocation invocation) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost("http://" + hostName + ":" + port);
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(invocation), ContentType.APPLICATION_JSON));
            String responseBody = httpClient.execute(httpPost, httpResponse -> {
                int status = httpResponse.getStatusLine().getStatusCode();
                if (status < 200 || status >= 300) {
                    // ... handle unsuccessful request
                    return String.valueOf(status);
                }
                HttpEntity entity = httpResponse.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            });
            // ... do something with response
            return responseBody;
        } catch (IOException e) {
            e.printStackTrace();
            // ... handle IO exception
        }
        return null;
    }

    public static String get(String hostName, Integer port, Invocation invocation) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet("http://" + hostName + ":" + port);
            String responseBody = httpClient.execute(httpGet, httpResponse -> {
                int status = httpResponse.getStatusLine().getStatusCode();
                if (status < 200 || status >= 300) {
                    // ... handle unsuccessful request
                }
                HttpEntity entity = httpResponse.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            });
            // ... do something with response
            return responseBody;
        } catch (IOException e) {
            e.printStackTrace();
            // ... handle IO exception
        }
        return null;
    }
}
